package com.jxstyle.modular.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxstyle.core.base.BaseController;
import com.jxstyle.core.common.page.PageInfo;
import com.jxstyle.modular.entity.Role;
import com.jxstyle.modular.entity.RoleMenu;
import com.jxstyle.modular.service.RoleMenuService;
import com.jxstyle.modular.service.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

	private final String prefix = "/role";
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleMenuService roleMenuService;
	
	@GetMapping(value = "")
	public String rolepage() {
		return prefix + "/list";
	}

	@GetMapping(value = "/add")
	public String add() {
		return prefix + "/add";
	}

	@GetMapping(value = "/edit/{id}")
	public String edit(@PathVariable int id, ModelMap modelMap) {
		modelMap.put("id", id);
		return prefix + "/edit";
	}

	@GetMapping(value = "/set/{id}")
	public String set(@PathVariable int id, ModelMap modelMap) {
		modelMap.put("id", id);
		return prefix + "/set";
	}

	@ResponseBody
	@PostMapping(value = "/add")
	public Boolean add(Role role) {
		roleService.save(role);
		return true;
	}

	@ResponseBody
	@PostMapping(value = "/edit")
	public Boolean edit(Role role) {
		roleService.updateById(role);
		return true;
	}

	@ResponseBody
	@PostMapping(value = "/delete/{id}")
	public Boolean delete(@PathVariable int id) {
		roleService.removeById(id);
		return true;
	}

	@ResponseBody
	@GetMapping(value = "/get/{id}")
	public Role get(@PathVariable int id) {
		Role role = roleService.getById(id);
		return role;
	}

	@ResponseBody
	@PostMapping("")
	public PageInfo<Role> page(PageInfo<Role> page) {
		QueryWrapper<Role> wrapper = new QueryWrapper<>();
		wrapper.orderByAsc("sort");
		return roleService.page(page, wrapper);
	}

	@ResponseBody
	@GetMapping(value = "/getSetNode/{id}")
	public List<Integer> getSetNode(@PathVariable int id) {
		QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
		wrapper.eq("roleid", id);
		List<RoleMenu> list = roleMenuService.list(wrapper);
		return list.stream().map(RoleMenu::getMenuid).collect(Collectors.toList());
	}

	@ResponseBody
	@PostMapping(value = "/set/{id}")
	public Boolean set(@PathVariable int id, String menuids) {
		roleMenuService.save(id,menuids);
		return true;
	}
}
